package com.kehong.pattern;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief 单例：饿汉式,但是不能实现懒加载
 * @email 122162005@qq.com
 * @date 2018-07-23
 */
public class Singleton {
    // 懒加载
    private static Singleton instance = new Singleton();
    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

/**
 * 懒汉式：线程不安全,但是能实现懒加载
 */
class Singleton02 {
    private static Singleton02 instance;

    private Singleton02() {}

    public static Singleton02 getInstance() {
        if (instance == null) {
            instance = new Singleton02();
        }

        return instance;
    }
}

/**
 * 懒汉式：线程安全,也能实现懒加载，但是效率低
 */
class Singleton03 {
    private static Singleton03 instance;

    private Singleton03() {}

    public synchronized static Singleton03 getInstance() {
        if (instance == null) {
            instance = new Singleton03();
        }

        return instance;
    }
}

/**
 * 双重锁检测:效率高，实现懒加载，同时有线程安全
 */
class Singleton04{
    private static Singleton04 instance;

    private Singleton04() {}

    public static Singleton04 getInstance() {
        if (instance == null) {
            synchronized (Singleton04.class) {
                if (instance == null) {
                    instance = new Singleton04();
                }
            }
        }

        return instance;
    }
}

enum Singleton05{
    INSTANCE
}


